package com.dupengcheng.wx.entity;

import com.dupengcheng.wx.redis.RedisUtil;
import com.dupengcheng.zp.V4OkHttpClientTest;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class WXTextHandler implements WXMessageTypeHandler{


    @Resource
    private RedisUtil redisUtil;
    private MessageTypeEnum type;

    @Override
    public MessageTypeEnum getType() {
        if (ObjectUtils.isEmpty(type)){
            this.type=MessageTypeEnum.TEXT;
        }
        return this.type;
    }

    @Override
    public String execute(Map<String, String> body) {
        //如果用户发送验证码、则发验证码给用户。
        String toUserName = body.get("ToUserName");
        String fromUserName = body.get("FromUserName");
        String text = body.get("Content");
        String vilCode="";

           if ("验证码".equals(text)){
               vilCode= String.valueOf(new Random().nextInt(9000)+1000);
               String replyContent="<xml>\n" +
                       "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                       "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                       "  <CreateTime>12345678</CreateTime>\n" +
                       "  <MsgType><![CDATA[text]]></MsgType>\n" +
                       "  <Content><![CDATA[你好,你的验证码是："+vilCode+"]]></Content>\n" +
                       "</xml>";
               String s = redisUtil.buildKey(vilCode);
               redisUtil.setNx(s,fromUserName,5L, TimeUnit.MINUTES);
               return replyContent;
           }else {
               String texts = body.get("Content");
               String msg=V4OkHttpClientTest.testInvoke(texts);
               String replyContent="<xml>\n" +
                       "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                       "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                       "  <CreateTime>12345678</CreateTime>\n" +
                       "  <MsgType><![CDATA[text]]></MsgType>\n" +
                       "  <Content><![CDATA["+msg+"]]></Content>\n" +
                       "</xml>";

               return replyContent;
           }

    }
}
